<?php
/**
 * Created by PhpStorm.
 * User: wzy12
 * Date: 2018/10/12
 * Time: 11:40
 */

namespace app\admin\model;


use think\Model;
use app\admin\validate\Article as Vali;

class Article extends Model
{
    public function operation($data){
        $query = $this -> where('title', $data['title']) -> where('cat_id', $data['cat_id']);
        $action = false;
        if(isset($data['id'])){
            $action = true;

            $query -> where('id', '<>', $data['id']);
        }else{
            $data['add_time'] = time();
            $data['author'] = session('user.username');
            $data['author_email'] = session('user.email');
        }
        // 判断该分类下是否有该文章
        $res = $query -> value('id');
        if($res){
            return echoArr(0, '该分类下的这个文章已存在');
        }

        // 验证
        $validate = new Vali();
        if(!$validate -> check($data)){
            return echoArr(0, $validate->getError());
        }

        $result = $this -> allowField(true) -> isUpdate($action) -> save($data);
        if(false === $result){
            return echoArr(0, $this -> getError());
        }else{
            return echoArr(1, '操作成功');
        }
    }

    public function del($data){
        // 验证
        $validate = new Vali();
        if(!$validate -> scene('del') -> check($data)){
            return echoArr(0, $validate->getError());
        }

        $result = $this -> destroy($data['id']);

        if(false === $result){
            return echoArr(0, '操作失败');
        }else{
            return echoArr(1, '操作成功');
        }
    }

    public function resList($where){
        $query = $this -> where(1);

        // 筛选条件
        $is_where = $where;
        unset($is_where['page']);
        if($is_where) {
            if ($where) {
                // 查询文章类型
                if ($where['cat_id']) {
                    $query->where('cat_id', $where['cat_id']);
                }

                // 查询文章名称
                if ($where['title']) {
                    $query->where('title', 'like', "%{$where['title']}%");
                }
            }
        }

        $arr['list'] = $query -> alias('a') -> join('ArticleCat c', 'a.cat_id = c.id') -> field('a.*,c.name cate_name') -> paginate(10, false, ['query'=>request()->param()]);

        // 文章分类列表
        $arr['article_cat'] = model('ArticleCat') -> select();

        return $arr;
    }

    /**
     * 更改状态
     */
    public function editStatus($data){
        // 验证
        $validate = new Vali();
        if(!$validate -> scene('status') -> check($data)){
            return echoArr(0, $validate->getError());
        }

        $result = $this -> allowField(true) -> isUpdate(true) -> save($data);

        if(false === $result){
            return echoArr(0, $this -> getError());
        }else{
            return echoArr(1, '操作成功');
        }
    }
}